# 表单类
from django import forms
from django.core.validators import RegexValidator,EmailValidator
from django.core.exceptions import ValidationError

# 自定义校验规则：两种方式
#     方式1：类
class myValid:
    def __call__(self, values):
        # 不能包含敏感字"admin"、"sb"
        if "sb" in values or "admin" in values:
            raise ValidationError(f"包含敏感字：{values}")


#       方法2：函数
def my_valid_func(values):
    if "sb" in values or "admin" in values:
        raise ValidationError(f"包含敏感字：{values}")


class UserForm(forms.Form):
    # username = forms.CharField(
    #     max_length=32,
    #     min_length=6,
    # )
    # password = forms.CharField(
    #     # 校验规则： 1、长度在6-32位，
    #     #           2、不能为纯数字，
    #     max_length=32,
    #     min_length=6,
    #     validators=[
    #         RegexValidator(r"\d+", "密码设置不能为纯数字"),
    #     ]
    # )
    username = forms.CharField(
        # label="用户名",
        max_length=32,
        min_length=6,
        validators=[
            my_valid_func,
            # 字母开头，
            RegexValidator(r"^[a-zA-Z]","必须以字母开头")
        ],
        error_messages = {"required": "必填"},
    )

    password = forms.CharField(
        # label="密码",
        min_length=6,
        max_length=32,
        required=True,
        validators=[
            # 不能是纯数字
            RegexValidator(r"\D+","密码不能为纯数字")
        ],
        error_messages = {"required": "必填"},
    )
    nick_name = forms.CharField(
        # label="昵称",
        min_length=2,
        max_length=32,
        required=True,
        validators=[
            myValid(),
            # 不能以数字开头（可以以汉字、字母开头）
            RegexValidator(r"^[\u4E00-\u9FA5A-Za-z]","昵称不能以数字开头")
        ],
        error_messages = {"required": "必填"},
    )
    phone = forms.CharField(
        # label="手机号",
        required=True,
        validators=[
            # 手机号码匹配规则：13/14/15/18/19开头
            RegexValidator("^(13[0-9]|14[5|7]|15[\d]|18[0|1|2|3|5|6|7|8|9]|19[1|2|3|4|5|6|7|8|9])\d{8}$","手机号格式不正确")
        ],
        error_messages = {"required": "必填"},
    )
    email = forms.CharField(
        # label="邮箱",
        required=True,
        validators=[
            EmailValidator("邮箱格式不正确。")
        ],
        error_messages = {"required": "必填"},
    )